package edu.jamestang.yeb.controller;

import edu.jamestang.yeb.entity.Admin;
import edu.jamestang.yeb.util.Resp;
import edu.jamestang.yeb.service.AdminService;
import edu.jamestang.yeb.vo.AdminLogin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @author JamesTang
 * @date 2021/12/13 13:25
 */
@Api(tags = "loginController")
@RestController
@AllArgsConstructor
@Slf4j
public class LoginController{


    @Autowired
    private AdminService adminService;

    @ApiOperation(value = "login")
    @PostMapping("/login")
    public Resp login(@RequestBody AdminLogin admin, HttpServletRequest request){

        return adminService.login(admin.getUsername(), admin.getPassword(), admin.getCode(), request);
    }


    @ApiOperation(value = "getUserInfo")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){

        if(null == principal){
            return null;
        }

        String username = principal.getName();
        Admin admin = adminService.getAdminByUsername(username);
        admin.setPassword(null);
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }


    @ApiOperation(value = "logout")
    @PostMapping("/logout")
    public Resp logout(){

        return Resp.success("logout");
    }
}
